﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using Cocbook_DTO;
using Cocbook_DAL;
using System.Diagnostics;
using System.Drawing.Printing;
using System.IO;
using GenCode128;

namespace Sale_and_manage
{
    public partial class frmAddOrder : DevComponents.DotNetBar.Metro.MetroForm
    {
        public frmAddOrder()
        {
            InitializeComponent();
            GetOrderID();
        }

        public int editRow = 0;
        public bool updateOrder = false;
        public Order oOrder = new Order();
        public static Int64 ISBN;
        public static bool status = true;
        public OrderDAL orderDAL = new OrderDAL();
        public BookDAL bookDAL = new BookDAL();
        public ProjectDAL projectDAL = new ProjectDAL();
        public static Project project = new Project();
        public Project_BookDAL pbDAL = new Project_BookDAL();
        public static List<SBook> lsb = null;
        public List<Order_Book> orderdetail = new List<Order_Book>();
        public Customer customer = new Customer(1,0, "Khách vãng lai", DateTime.Parse("1/1/1800"), "N/A","N/A", "N/A", "N/A", 0);
        public Book book = new Book();
        public int row = -1;
        public bool print = false;

        private void btnNameSearch_Click(object sender, EventArgs e)
        {
            frmBookFilter frm = new frmBookFilter();
            frm.chooseBookEvent += SelectedISBN;
            frm.ShowDialog();
            txtCopy.Focus();
        }

        public void SelectedISBN(Int64 ISBNNo)
        { 
            txtBarcode.Text = ISBNNo.ToString();
            LoadBook();
        }

        public void LoadBookFromFilter(Int64 isbn)
        {
            txtBarcode.Text = isbn.ToString();
            LoadBook();
            status = true;
        }

        public void ReadBarcode()
        {
            switch (txtBarcode.Text.Length)
            {
                case 7:
                    LoadOldOrder();
                    break;
                case 9:
                    LoadCustomer();
                    break;
                case 10:
                    if (dgvOrder.RowCount == 0) lblOrderID.Text = ShowOrderID((orderDAL.GetMaxOrderID() + 1));
                    LoadBook();
                    break;
                case 11:
                    if (dgvOrder.RowCount == 0) lblOrderID.Text = ShowOrderID((orderDAL.GetMaxOrderID() + 1));
                    LoadBook();
                    break;
                case 12:
                    if (dgvOrder.RowCount == 0) lblOrderID.Text = ShowOrderID((orderDAL.GetMaxOrderID() + 1));
                    LoadBook();
                    break;
                case 13:
                    if (dgvOrder.RowCount == 0) lblOrderID.Text = ShowOrderID((orderDAL.GetMaxOrderID() + 1));
                    LoadBook();
                    break;
            }
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            switch (keyData)
            {
                case Keys.F1:
                    btnNameSearch_Click(null,null);
                    break;
                case Keys.F2:
                    btnSave_Click(null,null);
                    break;
                case Keys.F3:
                    btnPrint_Click(null,null);
                    break;
                case Keys.F4:
                    btnClear_Click(null, null);
                    break;
                case Keys.Escape:
                    txtDiscount.Clear();
                    txtBarcode.Clear();
                    txtTitle.Clear();
                    txtCopy.Clear();
                    break;
            }

            return base.ProcessDialogKey(keyData);
        }

        public string ShowOrderID(int id)
        {
            string result = "0000000" + id.ToString();
            return result.Substring(result.Length - 7);
        }

        private void txtISBN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtPaid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsControl(e.KeyChar) && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
            if (Char.IsDigit(e.KeyChar) && txtPaid.Text == "0")
            {
                txtPaid.Text = e.KeyChar.ToString();
                txtPaid.SelectionStart = txtPaid.TextLength;
                e.Handled = true;
            }
        }




        public void LoadOldOrder()
        {
            oOrder = orderDAL.GetOrderByID(Convert.ToInt32(txtBarcode.Text));
            if (oOrder == null)
            {
                txtBarcode.Clear();
                txtBarcode.Focus();
                lblValidate.Text = "Không tìm thấy mã hóa đơn này, vui lòng nhập lại";
                highlighter1.SetHighlightColor(txtBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
            }
            else
            {
                lblOrderID.Text = oOrder.OrderID.ToString();
                Order_BookDAL obDAL = new Order_BookDAL();
                List<Order_Book> lob = obDAL.GetOrder_BookByOrderID(oOrder.OrderID);
                dgvOrder.Rows.Clear();
                for (int i = 0; i < lob.Count; i++)
                {
                    orderdetail.Add(lob[i]);
                    dgvOrder.Rows.Add(i + 1, lob[i].Book.ISBN, lob[i].Book.Title, lob[i].Copy, lob[i].Book.Price, lob[i].Discount, lob[i].Book.Price * (100 - lob[i].Discount) / 100);
                    dgvOrder.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
                }
                customer = oOrder.Customer;
                lblCustomerID.Text = ShowCustomerID(oOrder.Customer.CMND);
                lblCustomerName.Text = oOrder.Customer.CName;
                lblCustomerBonus.Text = oOrder.Customer.Points.ToString();
                txtBarcode.Clear();
                txtBarcode.Focus();
                updateOrder = true;
            }
        }
        public void LoadCustomer()
        {
            Customer c = new Customer();
            CustomerDAL cDAL = new CustomerDAL();
            c = cDAL.GetCustomerByCMND(Convert.ToInt32(txtBarcode.Text));
            if (c == null)
            {
                DialogResult d = MessageBox.Show("Không tồn tại mã khách hàng này, Bạn có muốn đăng kí thông tin cho khách hàng này không?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (d == DialogResult.Yes)
                {
                    frmAddCustomer frm = new frmAddCustomer();
                    frm.MdiParent = this.MdiParent;
                    frm.Show();
                }
                txtBarcode.Clear();
                txtBarcode.Focus();
                highlighter1.SetHighlightColor(txtBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
            }
            else
            {
                if (lblCustomerID.Text == "000000000" || lblCustomerID.Text == "")
                {
                    lblCustomerID.Text = ShowCustomerID(c.CMND);
                    lblCustomerName.Text = c.CName;
                    txtShipAddress.Text = c.CAddress;
                    customer = c;
                    lblCustomerBonus.Text = c.Points.ToString();
                    txtBarcode.Clear();
                    txtBarcode.Focus();
                }
                else
                {
                    if (MessageBox.Show("Hóa đơn hiện tại thuộc về khách hàng " + lblCustomerName.Text + ". Bạn có muốn thay thế hay không?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        customer = c;
                        lblCustomerID.Text = ShowCustomerID(c.CMND);
                        lblCustomerName.Text = c.CName;
                        lblCustomerBonus.Text = c.Points.ToString();
                        txtShipAddress.Text = c.CAddress;
                        txtBarcode.Clear();
                        txtBarcode.Focus();
                    }
                    else
                    {
                        txtBarcode.Clear();
                        txtBarcode.Focus();
                    }
                }
            }
        }

        public string ShowCustomerID(int id)
        {
            string result = "000000000" + id.ToString();
            result = result.Substring(result.Length - 9);
            return result;
        }

        public void LoadBook()
        {
            book = bookDAL.GetBookByISBN(Convert.ToInt64(txtBarcode.Text));
            if (book == null)
            {
                txtBarcode.Clear();
                highlighter1.SetHighlightColor(txtBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                lblValidate.Text = "Mã vạch sai. Vui lòng nhập lại.";
                txtBarcode.Focus();
            }
            else
            {
                txtTitle.Text = book.Title;
                txtCopy.Text = "1";
                txtCopy.Focus();
                txtCopy.SelectAll();
            }
        }

        private void frmAddOrder_Load(object sender, EventArgs e)
        {
            txtBarcode.Focus();
        }

        private void txtBarcode_TextChanged(object sender, EventArgs e)
        {
            if (txtBarcode.Text != "")
            {
                highlighter1.SetHighlightColor(txtBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.None);
                lblValidate.Text = "";
            }
        }

        private void txtBarcode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Validate vld = new Validate();
                if (vld.Barcode(txtBarcode.Text))
                {
                    ReadBarcode();
                }
                else
                {
                    highlighter1.SetHighlightColor(txtBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                    lblValidate.Text = "Mã vạch không hợp lệ, vui lòng quét lại.";
                    txtBarcode.Clear();
                    txtBarcode.Focus();
                }
            }
        }

        private void txtCopy_TextChanged(object sender, EventArgs e)
        {
            highlighter1.SetHighlightColor(txtCopy, DevComponents.DotNetBar.Validator.eHighlightColor.None);
            lblValidate.Text = "";
        }

        private void txtCopy_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtCopy_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (txtCopy.Text == "")
                {
                    highlighter1.SetHighlightColor(txtCopy, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                    txtCopy.Focus();
                    txtCopy.SelectAll();
                    lblValidate.Text = "Số lượng nhập vào không hợp lệ";
                }
                else
                {
                    if (txtBarcode.ReadOnly != true)
                    {
                        Order_Book ob = new Order_Book(null, book, 0, 0);
                        orderdetail.Add(ob);
                        double discount = 0;
                        bool skip = false;
                        if (txtDiscount.Text != "")
                        {
                            try
                            {
                                discount = Convert.ToDouble(txtDiscount.Text);
                            }
                            catch
                            {
                                skip = true;
                                lblValidate.Text = "Chiết khấu không hợp lệ";
                                txtDiscount.Focus();
                                txtDiscount.SelectAll();
                                highlighter1.SetHighlightColor(txtDiscount, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                            }
                        }
                        else
                        {
                            skip = true;
                            lblValidate.Text = "Chiết khấu không được bỏ trống";
                            txtDiscount.Focus();
                            txtDiscount.SelectAll();
                            highlighter1.SetHighlightColor(txtDiscount, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                        }
                        if (!skip)
                        {
                            AddBookToOrder(book.ISBN, book.Title, Convert.ToInt32(txtCopy.Text), book.Price, discount);
                            txtBarcode.Clear();
                            txtTitle.Clear();
                            txtCopy.Clear();
                            txtDiscount.Clear();
                        }
                    }
                    else
                    {
                        if (txtCopy.Text!="0")
                        {
                            dgvOrder[3, editRow].Value = Convert.ToInt32(txtCopy.Text);
                            dgvOrder[3, editRow].Value = Convert.ToDouble(txtDiscount.Text);
                            txtBarcode.Clear();
                            txtTitle.Clear();
                            txtCopy.Clear();
                            txtDiscount.Clear();
                            txtBarcode.ReadOnly = false;
                            txtBarcode.Focus();
                        }
                        else
                        {
                            dgvOrder.Rows.RemoveAt(editRow);
                            txtBarcode.Clear();
                            txtTitle.Clear();
                            txtCopy.Clear();
                            txtDiscount.Clear();
                            txtBarcode.ReadOnly = false;
                            txtBarcode.Focus();
                        }
                    }
                }
            }
            else
            {
                if (e.KeyCode == Keys.Escape)
                {
                    txtBarcode.ReadOnly = false;
                    txtCopy.Clear();
                    txtTitle.Clear();
                    txtDiscount.Clear();
                    txtBarcode.Clear();
                    txtBarcode.Focus();
                }
            }

        }

        public int GetBookIndex_dgvOrder(Int64 ISBN)
        {
            if (dgvOrder.RowCount == 0)
            {
                return 0;
            }
            else
            {
                int result = dgvOrder.RowCount;
                int i = 0;
                foreach (DataGridViewRow row in dgvOrder.Rows)
                {
                    if (row.Cells[1].Value.ToString() == ISBN.ToString())
                    {
                        result = i;
                        break;
                    }
                    else
                    {
                        i = i + 1;
                    }
                }
                return result;
            }
        }


        public void AddBookToOrder(Int64 isbn, string name, int copy, double price, double discount)
        {
            int id = GetBookIndex_dgvOrder(isbn);
            if (id == dgvOrder.RowCount || dgvOrder.RowCount == 0)
            {
                dgvOrder.Rows.Add(id + 1, isbn, name, copy, price, discount, price * (100 - discount) / 100);
            }
            else
            {
                dgvOrder.Rows[id].Cells[3].Value = (Convert.ToInt32(dgvOrder.Rows[id].Cells[3].Value) + copy);
            }
            txtBarcode.Clear();
            txtTitle.Clear();
            txtCopy.Clear();
            txtDiscount.Clear();
            txtBarcode.Focus();
        }

        private void dgvOrder_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if ((e.ColumnIndex == 7))
                {
                    dgvOrder.Rows.RemoveAt(e.RowIndex);
                }
                else
                {
                    txtBarcode.ReadOnly = true;
                    txtBarcode.Text = dgvOrder[1, e.RowIndex].Value.ToString();
                    txtTitle.Text = dgvOrder[2, e.RowIndex].Value.ToString();
                    txtCopy.Text = dgvOrder[3, e.RowIndex].Value.ToString();
                    txtDiscount.Text = dgvOrder[5, e.RowIndex].Value.ToString();
                    txtCopy.Focus();
                    txtCopy.SelectAll();
                    editRow = e.RowIndex;
                }
            }
        }

        private void dgvOrder_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                dgvOrder[e.ColumnIndex, e.RowIndex].Selected = true;
                RightClickMenu.Enabled = true;
                row = e.RowIndex;
            }
        }

        private void dgvOrder_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            txtTotal.Text = getTotal().ToString();
        }

        public double getTotal()
        {
            double sum = 0;
            for (int i = 0; i < dgvOrder.RowCount; i++)
            {
                sum = sum + Convert.ToDouble(dgvOrder.Rows[i].Cells[6].Value) * Convert.ToDouble(dgvOrder.Rows[i].Cells[3].Value);
            }
            return sum;
        }

        public void GetOrderID()
        {
            lblOrderID.Text = ShowOrderID((orderDAL.GetMaxOrderID() + 1));
        }

        private void dgvOrder_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                RightClickMenu.Enabled = false;
            }
        }

        private void dgvOrder_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            txtTotal.Text = getTotal().ToString();
        }

        private void dgvOrder_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            for (int i = 1; i <= dgvOrder.RowCount; i++)
            {
                dgvOrder.Rows[i - 1].Cells[0].Value = i;
            }
            orderdetail.RemoveAt(e.RowIndex);
            txtTotal.Text = getTotal().ToString();
        }

        private void txtPaid_Click(object sender, EventArgs e)
        {
            txtPaid.SelectionStart = txtPaid.TextLength;
            txtPaid.SelectAll();
        }

        private void txtPaid_TextChanged(object sender, EventArgs e)
        {
            if (rbtCash.Checked == true)
            {
                if (txtPaid.Text == "")
                {
                    txtPaid.Text = "0";
                }
                else
                {
                    txtPaid.Text = String.Format("{0:0,0}", double.Parse(txtPaid.Text));
                    txtChange.Text = (double.Parse(txtPaid.Text) - double.Parse(txtTotal.Text)).ToString();
                    txtPaid.SelectionStart = (txtPaid.TextLength);
                }
            }
        }

        private void txtPaid_Enter(object sender, EventArgs e)
        {
            txtPaid.SelectionStart = txtPaid.TextLength;
        }

        private void rbtBonus_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtBonus.Checked)
            {
                if (!((lblCustomerID.Text != "") && ((Convert.ToInt32(lblCustomerBonus.Text) * 0.05) >= Convert.ToInt32(txtTotal.Text))))
                {
                    MessageBox.Show("Số điểm hiện tại của bạn chưa thể thanh toán hóa đơn này");
                    rbtCash.Checked = true;
                }
                else
                {
                    txtPaid.Text = "0";
                    txtChange.Text = "0";
                }
            }
        }

        private void rbtLater_CheckedChanged(object sender, EventArgs e)
        {
            txtPaid.Text = "0";
            txtChange.Text = "0";
        }

        private void rbtCash_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtCash.Checked)
            {
                txtPaid.Text = (Convert.ToDouble(txtTotal.Text) + 1).ToString();
                txtPaid.Focus();
                txtPaid.SelectAll();
            }
        }

        private void frmAddOrder_Activated(object sender, EventArgs e)
        {
            if (status == false)
            {
                LoadBookFromFilter(ISBN);
            }
        }

        private void txtTotal_TextChanged(object sender, EventArgs e)
        {
            txtTotal.Text = String.Format("{0:0,0}", double.Parse(txtTotal.Text));
            if ((double.Parse(txtPaid.Text) - double.Parse(txtTotal.Text)) > 0)
            {
                txtChange.Text = (double.Parse(txtPaid.Text) - double.Parse(txtTotal.Text)).ToString();
            }
            else
                txtPaid.Text = txtTotal.Text;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Connection con = new Connection();
            if (con.CheckConnection())
            {
                if (double.Parse(txtChange.Text) < 0)
                {
                    txtPaid.Focus();
                    txtPaid.SelectAll();
                    MessageBox.Show("Số tiền của khách đưa không được nhỏ hơn thành tiền");

                }
                else
                {
                    if (dgvOrder.RowCount == 0)
                    {
                        MessageBox.Show("Danh sách rỗng!!!!!");
                        txtBarcode.Focus();
                    }
                    else
                    {
                        if (customer.CMND == 0)
                        {
                            MessageBox.Show("Bạn phải nhập thông tin của khách hàng trước");
                            txtBarcode.Focus();
                        }
                        else
                        {
                            int ckt = 0;
                            if (rbtCash.Checked)
                            {
                                ckt = 1;
                            }
                            else
                            {
                                if (rbtBonus.Checked)
                                {
                                    ckt = 2;
                                }
                                else
                                {
                                    ckt = 3;
                                }
                            }
                            if (updateOrder)
                            {
                                Order o = new Order(Convert.ToInt32(lblOrderID.Text), customer, DateTime.Now, txtShipAddress.Text, Convert.ToDouble(txtTotal.Text), 0, false, ckt);
                                orderDAL.UpdateOrder(o);
                                Order_BookDAL obDAL = new Order_BookDAL();
                                for (int i = 0; i < dgvOrder.RowCount; i++)
                                {
                                    orderdetail[i].Order = o;
                                    orderdetail[i].Copy = Convert.ToInt32(dgvOrder[3, i].Value);
                                    orderdetail[i].Discount = Convert.ToDouble(dgvOrder[3, i].Value);
                                    obDAL.UpdateOrder_Book(orderdetail[i]);
                                }
                                if (customer.CustomerID != 1)
                                {
                                    customer.Points = customer.Points + Convert.ToInt32(o.Total - oOrder.Total);
                                    CustomerDAL customerDAL = new CustomerDAL();
                                    customerDAL.UpdateCustomer(customer);
                                }
                                updateOrder = false;
                                if (print)
                                {
                                    Print();
                                }
                                print = false;
                                ClearAll();
                            }
                            else
                            {
                                Order o = new Order(Convert.ToInt32(lblOrderID.Text), customer, DateTime.Now, txtShipAddress.Text, Convert.ToDouble(txtTotal.Text), 0, false, ckt);
                                orderDAL.CreateOrder(o);
                                Order_BookDAL obDAL = new Order_BookDAL();
                                for (int i = 0; i < dgvOrder.RowCount; i++)
                                {
                                    orderdetail[i].Order = o;
                                    orderdetail[i].Copy = Convert.ToInt32(dgvOrder[3, i].Value);
                                    orderdetail[i].Discount = Convert.ToDouble(dgvOrder[5, i].Value);
                                    obDAL.CreateOrder_Book(orderdetail[i]);
                                }
                                if (customer.CustomerID != 1)
                                {
                                    customer.Points = customer.Points + Convert.ToInt32(o.Total);
                                    CustomerDAL customerDAL = new CustomerDAL();
                                    customerDAL.UpdateCustomer(customer);
                                }
                                if (print)
                                {
                                    Print();
                                }
                                print = false;
                                ClearAll();
                            }
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Không thể kết nối với Server!", "Connect error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Process.Start("ServerConfig.exe");
            }
        }

        public void ClearAll()
        {
            dgvOrder.Rows.Clear();
            txtBarcode.Clear();
            txtTotal.Text = "0";
            txtPaid.Text = "0";
            txtChange.Text = "0";
            rbtCash.Checked = true;
            GetOrderID();
            customer = new Customer(1, 0, "Khách vãng lai", DateTime.Parse("1/1/1800"), "N/A","N/A", "N/A", "N/A", 0);
            txtBarcode.Focus();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            DialogResult tb = (MessageBox.Show("Bạn xóa  danh sách không ?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning));
            if (tb == DialogResult.Yes)
            {
                ClearAll();
            }

        }

        public void Print()
        {
            PrintDocument doc = new PrintDocument();
            doc.PrintPage += new PrintPageEventHandler(Doc_print);
            doc.Print();
        }

        private void Doc_print(object sender, PrintPageEventArgs e)
        {
            Font time = new Font("Times New Roman", 11);
            Font time2 = new Font("Consolas", 7);
            StreamReader reader = new StreamReader(@"D:\abc.txt");
            Graphics g = e.Graphics;
            Image logo = System.Drawing.Bitmap.FromFile(@"logo.bmp");
            float lpg = 0;
            float ypos = 0;
            float tmargin = e.MarginBounds.Top;
            lpg = e.MarginBounds.Height / time.GetHeight(g);
            g.DrawImage(logo, 7, 15);
            g.DrawString("Công ty Cổ Phần COCBOOK", time, Brushes.Black, 5, 75, new StringFormat());
            ypos = 75 + time.GetHeight(g);
            g.DrawString("   www.cocbook.vn | fb/cocbook", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g) + 5;
            g.DrawString("     0939646679 | 0839918488", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("        Hóa đơn đặt sách         ", time, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time.GetHeight(g);
            g.DrawString("_________________________________", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("Địa chỉ nhận: ", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            if (txtShipAddress.Text.Length > 30)
            {
                g.DrawString(txtShipAddress.Text.Substring(0, 33), time2, Brushes.Black, 5, ypos, new StringFormat());
                ypos = ypos + time2.GetHeight(g);
                g.DrawString(txtShipAddress.Text.Substring(33), time2, Brushes.Black, 5, ypos, new StringFormat());
                ypos = ypos + time2.GetHeight(g);
            }
            else
            {
                g.DrawString(txtShipAddress.Text, time2, Brushes.Black, 5, ypos, new StringFormat());
                ypos = ypos + time2.GetHeight(g);
            }

            ypos = ypos + time2.GetHeight(g);
            g.DrawString("Tên hàng |CK |SL |Giá |Thành tiền", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("----------------------------------", time2, Brushes.Black, 5, ypos, new StringFormat());
            /////////////////////////
            int total = 0;
            for (int i = 0; i < dgvOrder.RowCount; i++)
            {
                ypos = ypos + time2.GetHeight(g);
                g.DrawString(dgvOrder[2,i].Value.ToString().Substring(0,30)+"... ", time2, Brushes.Black, 5, ypos, new StringFormat());
                ypos = ypos + time2.GetHeight(g);
                total += Convert.ToInt32(dgvOrder[3, i].Value);
                g.DrawString("          "+dgvOrder[5,i].Value.ToString()+"  "+dgvOrder[3,i].Value.ToString()+"  "+dgvOrder[4,i].Value.ToString()+"  "+
                            (Convert.ToInt32(dgvOrder[4,i].Value)*Convert.ToInt32(dgvOrder[3,i].Value)*(100-Convert.ToInt32(dgvOrder[5,i].Value))/100).ToString(), time2, Brushes.Black, 5, ypos, new StringFormat());
            }
            /////////////////////////
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("-------------------------------------", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("Tổng:       " + total + "       " + txtTotal.Text, time, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time.GetHeight(g);
            g.DrawString(DateTime.Now.ToString(), time2, Brushes.Black, 5, ypos, new StringFormat());
            Image billCode = Code128Rendering.MakeBarcodeImage(lblOrderID.Text, 1, true);

            ypos = ypos + time2.GetHeight(g);
            g.DrawImage(billCode, 10, ypos);

            ypos = ypos + 20;
            g.DrawString(lblOrderID.Text, time2, Brushes.Black, 5, ypos, new StringFormat());

            billCode = Code128Rendering.MakeBarcodeImage(lblCustomerID.Text, 1, true);

            ypos = ypos + time2.GetHeight(g) + 5;
            g.DrawImage(billCode, 10, ypos);
            ypos = ypos + 20;
            g.DrawString(lblCustomerID.Text, time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("_______________________________________", time2, Brushes.Black, 5, ypos, new StringFormat());
            ypos = ypos + time2.GetHeight(g);
            g.DrawString("Cocbook.vn Cảm ơn bạn đã mua sách", time2, Brushes.Black, 5, ypos, new StringFormat());
        }


        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (dgvOrder.RowCount > 0)
            {
                print = true;
                btnSave_Click(null, null);
            }
            
        }

        private void txtDiscount_TextChanged(object sender, EventArgs e)
        {
            highlighter1.SetHighlightColor(txtDiscount, DevComponents.DotNetBar.Validator.eHighlightColor.None);
            lblValidate.Text = "";
        }

        private void txtChange_TextChanged(object sender, EventArgs e)
        {
            txtChange.Text = String.Format("{0:0,0.0}", double.Parse(txtChange.Text));
        }
    }
}